package com.bianxingji.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bianxingji.dto.BxjStarDto;
import com.bianxingji.mapper.BxjMediaFilesMapper;
import com.bianxingji.mapper.BxjStarDetailMapper;
import com.bianxingji.mapper.BxjStarMapper;
import com.bianxingji.mapper.BxjSysQuarterMapper;
import com.bianxingji.model.PageResult;
import com.bianxingji.po.BxjMediaFiles;
import com.bianxingji.po.BxjStar;
import com.bianxingji.po.BxjStarDetail;
import com.bianxingji.po.BxjSysQuarter;
import com.bianxingji.service.BxjMediaFileService;
import com.bianxingji.service.BxjStarService;
import com.bianxingji.utils.Base64Util;
import com.bianxingji.vo.BxjStarVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wy
 */
@Slf4j
@Service
public class BxjStarServiceImpl extends ServiceImpl<BxjStarMapper, BxjStar> implements BxjStarService {

    @Autowired
    private BxjStarMapper bxjStarMapper;
    @Autowired
    private BxjStarDetailMapper bxjStarDetailMapper;
    @Autowired
    private BxjMediaFilesMapper bxjMediaFilesMapper;
    @Autowired
    private BxjSysQuarterMapper bxjSysQuarterMapper;

    @Override
    public PageResult<BxjStar> getRandomStarList() {
        PageResult<BxjStar> listPageResult = new PageResult<>();
        Page<BxjStar> page = new Page<>(1,2);
        Page<BxjStar> bxjStarPage = bxjStarMapper.selectPage(page,null);
        List<BxjStar> records = bxjStarPage.getRecords();
        for (BxjStar bxjStar : records) {
            bxjStar.setAvatar(bxjMediaFilesMapper.selectOne(new LambdaQueryWrapper<BxjMediaFiles>()
                    .eq(BxjMediaFiles::getId, bxjStar.getAvatar())).getUrl());
        }
        listPageResult.setList(records);
        listPageResult.setPageSize(2);
        listPageResult.setCurrentPage(1);
        listPageResult.setPageSize(records.size());
        return listPageResult;
    }

    @Override
    public PageResult<BxjStarVo> getPage(Map<String,Object> map) {
        PageResult<BxjStarVo> listPageResult = new PageResult<>();
        // 获取分页参数
        int currentPage = (Integer) map.get("currentPage");
        int pageSize = (Integer) map.get("pageSize");
        Page<BxjStar> page = new Page<>(currentPage, pageSize);

        LambdaQueryWrapper<BxjStar> bxjStarLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bxjStarLambdaQueryWrapper.like(!Objects.isNull(map.get("name")),BxjStar::getName, map.get("name"));
        bxjStarLambdaQueryWrapper.like(!Objects.isNull(map.get("status")),BxjStar::getStatus, map.get("status"));

        Page<BxjStar> bxjStarPage = bxjStarMapper.selectPage(page,bxjStarLambdaQueryWrapper);

        // 处理查询结果
        List<BxjStarVo> bxjStarVos = bxjStarPage.getRecords().stream().map(bxjStar -> {
            // 获取头像URL
//            String avatarUrl = bxjMediaFilesMapper.selectOne(new LambdaQueryWrapper<BxjMediaFiles>()
//                            .eq(BxjMediaFiles::getId, bxjStar.getAvatar()))
//                    .getUrl() ;
            String avatarUrl ="https://pics0.baidu.com/feed/a50f4bfbfbedab6414b357fe7b068dcd78311e8c.jpeg?token=b0014c84e3e1ac8feed2e683f8137898";
            // 获取详细信息
            LambdaQueryWrapper<BxjStarDetail> detailQueryWrapper = new LambdaQueryWrapper<BxjStarDetail>()
                    .eq(BxjStarDetail::getStarId, bxjStar.getId())
                    .like(map.get("des") != null, BxjStarDetail::getDes, map.get("des"));

            BxjStarDetail bxjStarDetail = bxjStarDetailMapper.selectOne(detailQueryWrapper);
            if(Objects.isNull(bxjStarDetail)) return null;

            String schedule = Arrays.stream(bxjStarDetail.getSchedule().split(","))
                    .map(scheduleId -> bxjSysQuarterMapper.selectOne(new LambdaQueryWrapper<BxjSysQuarter>()
                            .eq(BxjSysQuarter::getId, scheduleId)))
                    .map(BxjSysQuarter::getName)
                    .collect(Collectors.joining(","));

            // 返回构造的Vo对象
            return new BxjStarVo(
                    bxjStar.getId(),
                    bxjStar.getName(),
                    avatarUrl,
                    schedule,
                    bxjStarDetail.getDes(),
                    bxjStar.getStatus(),
                    bxjStarDetail.getSchedule().split(",")
            );
        }).filter(Objects::nonNull).collect(Collectors.toList());
        listPageResult.setTotal(bxjStarPage.getTotal());
        listPageResult.setPageSize(pageSize);
        listPageResult.setCurrentPage(currentPage);
        listPageResult.setList(bxjStarVos);
        return listPageResult;
    }

    public boolean updateStatus(Integer id, Integer status) {
        // 构造查询条件，根据 id 找到对应的明星记录
        BxjStar bxjStar = bxjStarMapper.selectById(id);
        // 如果找不到对应的明星记录，返回 false
        if (bxjStar == null) {
            return false;
        }
        // 设置新的状态
        bxjStar.setStatus(status);
        // 如果更新影响的行数大于 0，表示更新成功
        return  bxjStarMapper.updateById(bxjStar)>0;
    }

    @Override
    @Transactional
    public boolean saveOrUpdateStar(BxjStarDto bxjStarDto) {
        //默认图片
        if(bxjStarDto.getAvatar()==null||bxjStarDto.getAvatar()==""){
            bxjStarDto.setAvatar("666");
        }
        /*这里根据名字判断*/
        BxjStar bxjStar = bxjStarMapper.selectOne(new LambdaQueryWrapper<BxjStar>().eq(BxjStar::getName, bxjStarDto.getName()));
        if(Objects.isNull(bxjStar)){
            BxjStar bs = new BxjStar();
            BeanUtils.copyProperties(bxjStarDto,bs);
            bxjStarMapper.insert(bs);
           return bxjStarDetailMapper.insert(new BxjStarDetail(bs.getId(),bxjStarDto.getDes(),bxjStarDto.getSchedule()))>0;
        }
        bxjStar.setStatus(bxjStarDto.getStatus());
        bxjStarMapper.updateById(bxjStar);
        return bxjStarDetailMapper.update(new BxjStarDetail(bxjStar.getId(),bxjStarDto.getDes(),bxjStarDto.getSchedule()),
                new LambdaQueryWrapper<BxjStarDetail>().eq(BxjStarDetail::getStarId,bxjStar.getId()))>0;
    }

    @Override
    @Transactional
    public boolean deleteStar(BxjStarDto bxjStarDto) {
        bxjStarMapper.deleteById(bxjStarDto.getId());
        return bxjStarDetailMapper
                .delete(new LambdaQueryWrapper<BxjStarDetail>()
                        .eq(BxjStarDetail::getStarId,bxjStarDto.getId()))>0;
    }

    @Override
    @Transactional
    public boolean deleteBatch(String[] ids) {
        // 批量删除 bxjStar 表中的记录
        bxjStarMapper.deleteBatchIds(Arrays.asList(ids));
        // 获取所有需要删除的 BxjStarDetail starId
        List<String> starIds = Arrays.stream(ids)
                .map(id -> bxjStarDetailMapper.selectOne(new LambdaQueryWrapper<BxjStarDetail>().eq(BxjStarDetail::getStarId, id)))
                .filter(Objects::nonNull)
                .map(BxjStarDetail::getStarId) // 提取 starId
                .collect(Collectors.toList());
        // 批量删除 BxjStarDetail
        if (!starIds.isEmpty()) {
            bxjStarDetailMapper.delete(new LambdaQueryWrapper<BxjStarDetail>().in(BxjStarDetail::getStarId, starIds));
        }
        return true;
    }


    @DubboReference
    private BxjMediaFileService bxjMediaFileService;

    @Override
    public boolean uploadAvatar(BxjStar bxjStar) throws IOException {

        // 提取文件类型（MIME 类型）
        String fileType = Base64Util.extractFileType(bxjStar.getAvatar());
        if (fileType == null) {
            throw new IllegalArgumentException("无法提取文件类型");
        }
        byte[] bytes = Base64Util.decodeBase64ToImage(bxjStar.getAvatar());

        // 调用异步上传方法
        RpcContext.getContext().asyncCall(() -> bxjMediaFileService.uploadAvatar(bytes,fileType.split("/")[1]));

        return true;
    }
}
